package com.itany.boot.controller;

import com.itany.boot.entity.User;
import com.itany.boot.exception.UserNotExistException;
import com.itany.boot.service.UserService;
import com.itany.boot.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author shixiaojun@itany
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 查询:@GetMapping
    // 添加:@PostMapping
    // 修改:@PutMapping
    // 删除:@DeleteMapping

    // 在一个Controller中,不同请求可以同时存在

    @GetMapping
    public ResponseResult findAll() {
        List<User> users = userService.findAll();
        return ResponseResult.success(users);
    }

    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        return ResponseResult.success(user);
    }

    @GetMapping("/login")
    public ResponseResult login(String username, String password) {
        User user = null;
        try {
            user = userService.login(username, password);
            return ResponseResult.success(user);
        } catch (UserNotExistException e) {
            return ResponseResult.fail(e.getMessage());
        }

    }

    @PostMapping
    public ResponseResult addUser(User user) {
        userService.addUser(user);
        return ResponseResult.success();
    }

    @PutMapping
    public ResponseResult modifyUser(User user){
        userService.modifyUser(user);
        return ResponseResult.success();
    }

    @DeleteMapping("/{id}")
    public ResponseResult removeUser(@PathVariable("id") Integer id){
        userService.removeUser(id);
        return ResponseResult.success();
    }
}
